package cn.wowjoy.office.materialinspection.xunjian.task;

import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.ScaleAnimation;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnRefreshListener;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.customview.MaskFramLayout;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.response.InspectTaskDtlVO;
import cn.wowjoy.office.data.response.InspectionTaskControllerResponse;
import cn.wowjoy.office.data.response.SingleTaskController;
import cn.wowjoy.office.databinding.ActivityPatrolTaskBinding;
import cn.wowjoy.office.materialinspection.xunjian.detail.DeviceDetail2Activity;
import cn.wowjoy.office.utils.dialog.DialogUtils;

public class PatrolTaskActivity extends NewBaseActivity<ActivityPatrolTaskBinding, PatrolTaskViewModel> implements View.OnClickListener {
    private static final int REQUEST_CODE = 0x00000011;
    boolean isSelected = false;
    private MDialog mDialog; //back提示
    private MDialog submitDialog;//提交失败
//    private   TranslateAnimation mShowAction;
//    private   TranslateAnimation mHiddenAction;

    private ScaleAnimation mShowAction;
    private ScaleAnimation mHiddenAction;
    String taskId;   //唯一索引
    boolean isDone;  // 是否完成
    private String key; //关键词


    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViewModel(viewModel);
        
        binding.patrolTaskTitle.titleTextTv.setText("巡检任务详情");
        binding.patrolTaskTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.patrolTaskTitle.titleBackTv.setText("");
        binding.patrolTaskTitle.titleBackLl.setOnClickListener(this);


        taskId = getIntent().getExtras().getString("taskId");
        isDone = getIntent().getExtras().getBoolean("isDone");
        if (null != taskId && !"".equals(taskId)) {
            setFilterText(filter);
        }
        if(isDone){
            binding.patrolTaskTitle.titleMenuConfirm.setText("查看总结");
        }else{
            binding.patrolTaskTitle.titleMenuConfirm.setText("下一步");
        }
        binding.patrolTaskTitle.titleMenuConfirm.setTextColor(getResources().getColor(R.color.white));
        binding.patrolTaskTitle.titleMenuConfirm.setOnClickListener(this);
        binding.patrolTaskTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
        binding.stateNoCheck.setOnClickListener(this);
        binding.stateDeviceError.setOnClickListener(this);
        binding.stateNotLookError.setOnClickListener(this);
        binding.stateStop.setOnClickListener(this);
        binding.stateNormal.setOnClickListener(this);
        binding.stateAll.setOnClickListener(this);
        binding.stateDeviceRepair.setOnClickListener(this);

        binding.rvPatrol.setLayoutManager(new LinearLayoutManager(this));
        binding.rvPatrol.setAdapter(viewModel.wladapter);
        binding.rvPatrol.setEmptyView(binding.emptyView.getRoot());
        binding.rvPatrol.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                //下拉刷新 请求服务器新数据
                if (null != taskId) {
                    setFilterText(filter);
                }
            }
        });

        binding.divider.setAlpha(0.2F);
        initSearch();//搜索栏
        initFilter();//初始化Filter
        initObserve();
    }
    private void initObserve(){
        viewModel.getResponse().observe(this, new Observer<LiveDataWrapper<InspectionTaskControllerResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<InspectionTaskControllerResponse> inspectionTaskControllerResponseLiveDataWrapper) {
                switch (inspectionTaskControllerResponseLiveDataWrapper.status){
                    case LOADING:
                        DialogUtils.waitingDialog(PatrolTaskActivity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(PatrolTaskActivity.this);
                        updateUI(inspectionTaskControllerResponseLiveDataWrapper.data,filter);
                        break;
                    case ERROR:
                        DialogUtils.dismiss(PatrolTaskActivity.this);
                        handleException(inspectionTaskControllerResponseLiveDataWrapper.error,true);
                        break;
                }
            }
        });

        viewModel.getLoad().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean aBoolean) {
                setFilterText(filter.trim(),aBoolean.booleanValue());
            }
        });

        viewModel.getJump().observe(this, new Observer<InspectTaskDtlVO>() {
            @Override
            public void onChanged(@Nullable InspectTaskDtlVO inspectTaskDtlVO) {
                jump(inspectTaskDtlVO);
            }
        });
    }
    private void initSearch() {
        binding.searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                hideSoftInput();
                key = binding.searchEditText.getText().toString().trim();
                switchFilter2(key, true);
                return true;
            }
        });
        binding.searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO：联网模糊查询
//                if(s.toString().isEmpty()){
//                    //  搜索清空的时候
//                    mPatrolTaskPresenter.getInspectTaskControllerByPageSize(taskId, "", "", "", "", "", true, filter);
//                }
                if (!TextUtils.isEmpty(binding.searchEditText.getText().toString())) {
                    binding.delete.setVisibility(View.VISIBLE);
                } else {
                    binding.delete.setVisibility(View.GONE);
                    key = null;
                }
            }
        });
        binding.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.searchEditText.setText("");
            }
        });
    }

    private void initFilter() {
        binding.tvFilterPatrolTask.setSelected(false);
        binding.tvFilterPatrolTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSelected) {
                    binding.maskLr.setVisibility(View.GONE);
                    isSelected = false;
                    binding.tvFilterPatrolTask.setSelected(false);

                    binding.rlAnim.setVisibility(View.VISIBLE);

                } else {
                    binding.maskLr.setVisibility(View.VISIBLE);
                    isSelected = true;
                    binding.tvFilterPatrolTask.setSelected(true);
                }
            }
        });
        //展示巡检设备清单的状态筛选 下拉
        binding.maskLr.setDimissListener(new MaskFramLayout.DimissListener() {
            @Override
            public void onDismiss() {
                isSelected = false;
                binding.tvFilterPatrolTask.setSelected(false);
                binding.rlAnim.setVisibility(View.VISIBLE);
                binding.maskLr.setVisibility(View.GONE);

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
//        openBroadCast();
        if (!isDone) {
            openBroadCast();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        closeBroadCast();
        if (!isDone) {
            closeBroadCast();
        }
    }

    @Override
    public void onBackPressed() {
        if (!isDone) {
            mDialog = CreateDialog.infoDialog(PatrolTaskActivity.this, "提醒", "该巡检任务还未提交，是否退出", "否", "是", v12 -> {
                if (null != mDialog) {
                    mDialog.cancel();
                }
            }, v1 -> {
                if (null != mDialog) {
                    mDialog.cancel();
                    finish();
                }
            });
        } else {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case Constants.EIDT_CODE:
                    //下一步提交完成
                    if(resultCode == Constants.RESULT_OK) {
                        finish();
                    }
                    break;
                case Constants.RESULT_CODE:
                    if (null != taskId && !"".equals(taskId)) {
                        setFilterText(filter);
                    }
                    break;

        }
    }

    public void updateUI(InspectionTaskControllerResponse taskListResponse, String status) {
//        if (viewModel.mItemRvDetailAdapter.getDateSize() == 0) {
//            binding.tvFilterPatrolTask.setText(status);
//        } else {
//            binding.tvFilterPatrolTask.setText(status + "(" + viewModel.mItemRvDetailAdapter.getDateSize() + ")");
//        }

        if (isDone) {
            binding.rlPeopleDoneTask.setVisibility(View.VISIBLE);
            binding.rlXunjianTimeTask.setVisibility(View.VISIBLE);
        } else {
            binding.rlPeopleDoneTask.setVisibility(View.GONE);
            binding.rlXunjianTimeTask.setVisibility(View.GONE);
        }
        SingleTaskController single = taskListResponse.getSingle();
        if(null != single){
            if (single.getTotalCount() == 0) {
                binding.tvFilterPatrolTask.setText(status);
            } else {
                binding.tvFilterPatrolTask.setText(status + "(" + single.getTotalCount() + ")");
            }
            binding.tvNumberPatroltask.setText(single.getBillNo());
            binding.tvPeopleNamePatroltask.setText(single.getInspectUserName());
            binding.tvRoomPatroltask.setText(single.getUseDepartmentName());
            binding.tvMaterialTimePatroltask.setText(single.getInspecDatetime());
        }

    }

    // 筛选菜单的文字
    public void setFilterText(String state) {
        isSelected = false;
        binding.tvFilterPatrolTask.setSelected(false);
        binding.maskLr.setVisibility(View.GONE);
        binding.rlAnim.setVisibility(View.VISIBLE);
        binding.tvFilterPatrolTask.setText(state);
        switchRequest(state, true);
    }

    // 筛选菜单的文字
    public void setFilterText(String state, boolean ref) {
        isSelected = false;
        binding.tvFilterPatrolTask.setSelected(false);
        binding.maskLr.setVisibility(View.GONE);
        binding.tvFilterPatrolTask.setText(state);
        switchRequest(state, ref);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back_ll:
                //弹框提示
                if (!isDone) {
                    mDialog = CreateDialog.infoDialog(PatrolTaskActivity.this, "提醒", "该巡检任务还未提交，是否退出", "否", "是", v12 -> {
                        if (null != mDialog) {
                            mDialog.cancel();
                        }
                    }, v1 -> {
                        if (null != mDialog) {
                            mDialog.cancel();
                            finish();
                        }
                    });
                } else {
                    finish();
                }
                break;
            case R.id.title_menu_confirm:
                //未完成Task 提交任务   ----检查是否全部做过，并且提示
                if (null != viewModel.single) {
                    if (null == viewModel.single.getId() || null == viewModel.single.getUseDepartmentName()) {
                        finish();
                        return;
                    }
                    //判断当前是否做完
                    if (null == viewModel.single.getIsDone() || "n".equalsIgnoreCase(viewModel.single.getIsDone())) {
                        submitDialog = CreateDialog.submitDialog(PatrolTaskActivity.this, "提交失败", "当前巡检任务还有设备未巡检,请巡检完成后提交",101,null,"确定");
                        return;
                    }
                    EditAdviceActivity.lanuch(isDone,viewModel.single,PatrolTaskActivity.this);
                }

                break;
            case R.id.state_stop:
                setFilterText("停用");
                break;
            case R.id.state_not_look_error:
                setFilterText("外观异常");
                break;
            case R.id.state_all:
                setFilterText("全部");
                break;
            case R.id.state_no_check:
                setFilterText("未检测");
                break;
            case R.id.state_normal:
                setFilterText("正常");
                break;
            case R.id.state_device_error:
                setFilterText("设备未找到");
                break;
            case R.id.state_device_repair:
                setFilterText("维修");
                break;
        }
    }

    public void switchFilter2(String billInfo, boolean refresh) {
        switch (filter) {
            case "全部":
                viewModel.getInspectTaskControllerByPageSize(taskId, billInfo, "", "", "", "", refresh, filter);
                break;
            case "设备异常":
                viewModel.getInspectTaskControllerByPageSize(taskId, billInfo, "", "", "", "n", refresh, filter);
                break;
            case "外观异常":
                viewModel.getInspectTaskControllerByPageSize(taskId, billInfo, "", "", "n", "y", refresh, filter);
                break;
            case "未检测":
                viewModel.getInspectTaskControllerByPageSize(taskId, billInfo, "", "n", "", "", refresh, filter);
                break;
            case "正常":
                viewModel.getInspectTaskControllerByPageSize(taskId, billInfo, "y", "", "y", "y", refresh, filter);
                break;
            case "设备未找到":
                viewModel.getInspectTaskControllerByPageSize(taskId, billInfo, "n", "", "", "", refresh, filter);
                break;

            default:
                viewModel.getInspectTaskControllerByPageSize(taskId, billInfo, "", "", "", "", refresh, filter);
                break;
        }
    }

    public void switchFilter(String string, boolean refresh) {
        switch (string) {
            case "全部":
                filter = "全部";
                viewModel.getInspectTaskControllerByPageSize(taskId, "", "", "", "", "", refresh, filter);
                break;
            case "停用":
                filter = "停用";
                viewModel.getInspectTaskControllerByPageSize(taskId, "", "", "", "", "n","y","y","y","y", refresh, filter);
                break;
            case "外观异常":
                filter = "外观异常";
                viewModel.getInspectTaskControllerByPageSize(taskId, "", "", "", "n", "", refresh, filter);
                break;
            case "未检测":
                filter = "未检测";
                viewModel.getInspectTaskControllerByPageSize(taskId, "", "", "n", "", "", refresh, filter);
                break;
            case "正常":
                filter = "正常";
                viewModel.getInspectTaskControllerByPageSize(taskId, "", "y", "", "", "y","y","y","y","y", refresh, filter);
                break;
            case "设备未找到":
                filter = "设备未找到";
                viewModel.getInspectTaskControllerByPageSize(taskId, "", "n", "", "", "", refresh, filter);
                break;
            case "维修":
                filter = "维修";
                viewModel.getInspectTaskControllerByPageSize(taskId, "", "y", "", "", "m", refresh, filter);
                break;
            default:
                viewModel.getInspectTaskControllerByPageSize(taskId, "", "", "", "", "", refresh, filter);
                break;
        }
    }

    public String filter = "全部";

    public void switchRequest(String text, boolean refresh) {
        if (null == text || "".equals(text)) {
            viewModel.getInspectTaskControllerByPageSize(taskId, "", "", "", "", "", refresh, filter);
            return;
        }
        switchFilter(text, refresh);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mDialog) {
            mDialog.cancel();
        }
        if (null != submitDialog) {
            submitDialog.cancel();
        }
    }

    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
        String key = msg;
//        //扫到的二维码信息 填入到搜索栏中
//        if (null != key) {
//            binding.searchEditText.setText(key);
//            binding.searchEditText.setSelection(key.length());
//        }
        Intent intent = new Intent(this, DeviceDetail2Activity.class);
        intent.putExtra("qrCode", key);
        if (null != viewModel.single.getId()) {
            intent.putExtra("totalId", viewModel.single.getId());
        }
        intent.putExtra("isDone", false);
        intent.putExtra("isShow", false);
//        intent.putExtra("isFind", true);
        startActivityForResult(intent, Constants.RESULT_CODE);
    }


    @Override
    protected void refreshError() {
        super.refreshError();
        setFilterText(binding.tvFilterPatrolTask.getText().toString().trim());
    }

    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.flEmpty;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_patrol_task;
    }

    @Override
    protected Class<PatrolTaskViewModel> getViewModel() {
        return PatrolTaskViewModel.class;
    }

    public void  jump(InspectTaskDtlVO inspectTaskDtlVO){
        Intent intent = new Intent(this, DeviceDetail2Activity.class);
        intent.putExtra("totalId", viewModel.single.getId());
        intent.putExtra("taskDtlId", inspectTaskDtlVO.getId());
        intent.putExtra("isDone", isDone);
        intent.putExtra("isShow", true);
        startActivityForResult(intent, Constants.RESULT_CODE);
    }
}
